package com.zzx.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zzx.RoleEnum;
import com.zzx.config.UserContext;
import com.zzx.entity.TCompany;
import com.zzx.entity.TUser;
import com.zzx.entity.vo.DecryptUserInfo;
import com.zzx.entity.vo.WxLoginResult;
import com.zzx.service.TCompanyService;
import com.zzx.service.TUserService;
import com.zzx.mapper.TUserMapper;
import com.zzx.utils.HttpClientUtil;
import com.zzx.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;

/**
* @author zzx
* @description 针对表【t_wx_user(用户表)】的数据库操作Service实现
* @createDate 2025-05-21 22:41:50
*/
@Service
@Slf4j
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService {

    @Value("${wechat.appId}")
    private String appId;

    @Value("${wechat.secret}")
    private String secret;

    @Value("${wechat.grantType}")
    private String grantType;

    @Resource
    private TCompanyService tCompanyService;

    @Override
    public TUser getByOpenId(String openId) {
        return this.getOne(new LambdaQueryWrapper<TUser>().eq(TUser::getOpenId, openId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject wxLogin(String code) {
        if (Strings.isBlank(code)) {
            throw new RuntimeException("请传code");
        }
//        // 1. 调用微信接口获取session_key和openid
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> params = new HashMap<>();
        params.put("appid", appId);
        params.put("secret", secret);
        params.put("js_code", code);
        params.put("grant_type", grantType);
        String result = HttpClientUtil.sendGet(url, params);
//        String result = "{\"session_key\":\"fTng+tmvxwYVHqRRvlFDJw==\",\"openid\":\"oW0Pw605ISTCR30YUOj6-XtsmDQY\"}";
        WxLoginResult wxLoginResult = JSONUtil.toBean(result, WxLoginResult.class);

        if (!ObjectUtils.isEmpty((wxLoginResult.getErrcode()))) {
            throw new RuntimeException("Invalid code");
        }

        // 2. 根据openid查询用户是否存在
        TUser user = this.getByOpenId(wxLoginResult.getOpenid());

        // 3. 如果用户不存在则创建新用户
        if (user == null) {
            user = new TUser();
            user.setUserCategory(1);
            user.setOpenId(wxLoginResult.getOpenid());
            user.setUserName("计件用户");
            user.setRole(RoleEnum.EMPLOYEE.getCode());
            user.setSessionKey(wxLoginResult.getSession_key());
            user.setUnionId(wxLoginResult.getUnionid());
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            user.setUserId(IdUtil.getSnowflakeNextId());
            this.save(user);
        } else {
            // 更新用户信息
//            user.setUpdateTime(LocalDateTime.now());
//            user.setOpenId(wxLoginResult.getOpenid());
//            user.setSessionKey(wxLoginResult.getSession_key());
//            this.updateById(user);
        }

        // 4. 生成自定义登录态token
        Map<String, Object> claims = new HashMap<>();
        claims.put("openId", user.getOpenId());
        claims.put("userId", user.getUserId());
        claims.put("userCategory", user.getUserCategory());
        if (!ObjectUtils.isEmpty(user.getCompanyId())) {
            claims.put("companyId", user.getCompanyId());
        }
        String token = JWTUtil.createToken(claims);

        JSONObject res = new JSONObject();
        res.put("token",token);
        res.put("openId",user.getOpenId());
        res.put("userInfo",user);
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TUser param) {
        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>(TUser.class);
        wrapper.eq(TUser::getCompanyId, UserContext.getCompanyId());
        wrapper.eq(TUser::getUserName, param.getUserName());
        if (ObjectUtils.isEmpty(param.getUserId())) {
            param.setUserId(IdUtil.getSnowflakeNextId());
            param.setCreateBy(UserContext.getUserId());
            param.setCreateTime(LocalDateTime.now());
        } else {
            wrapper.ne(TUser::getUserId, param.getUserId());
            param.setUpdateBy(UserContext.getUserId());
            param.setUpdateTime(LocalDateTime.now());
        }
        List<TUser> tUsers = this.getBaseMapper().selectList(wrapper);
        if (!tUsers.isEmpty()) {
            throw new RuntimeException("名称重复");
        }
        this.saveOrUpdate(param);
    }

    @Override
    public List<TUser> selectBy(TUser param) {

        LambdaQueryWrapper<TUser> wrapper = new LambdaQueryWrapper<>(TUser.class);
        if (!ObjectUtils.isEmpty(param.getUserName())) {
            wrapper.like(TUser::getUserName, param.getUserName());
        }
        if (!ObjectUtils.isEmpty(param.getUserNum())) {
            wrapper.like(TUser::getUserNum, param.getUserNum());
        }
        if (!ObjectUtils.isEmpty(param.getUserZw())) {
            wrapper.eq(TUser::getUserZw, param.getUserZw());
        }
        if (!ObjectUtils.isEmpty(param.getUserId())) {
            wrapper.eq(TUser::getUserId, param.getUserId());
        }
        wrapper.eq(TUser::getCompanyId, UserContext.getCompanyId());
        List<TUser> tTUserList = this.getBaseMapper().selectList(wrapper);

//        MPJLambdaWrapper<TUser> mpjLambdaWrapper = new MPJLambdaWrapper();
//        mpjLambdaWrapper.selectAll(TUser.class);
//        mpjLambdaWrapper.select(TCompany::getCompanyName);
//        mpjLambdaWrapper.leftJoin(TCompany.class, TCompany::getCompanyId, TUser::getCompanyId);
//        this.getBaseMapper().selectJoinList(TUser.class, mpjLambdaWrapper);
        return tTUserList;
    }

    @Override
    @Transactional (rollbackFor = Exception.class)
    public void deleteById(TUser param) {
        this.removeById(param.getUserId());
    }

    @Override
    public TUser findById(Long userId) {
        TUser tUser = this.getById(userId);
        return tUser;
    }

    @Override
    public JSONObject decryptUserInfo(DecryptUserInfo decryptUserInfo) {
//        JSONObject jsonObject = new JSONObject();
//        try {
//            byte[] key = Base64.getDecoder().decode(decryptUserInfo.getSessionKey());
//            byte[] ivBytes = Base64.getDecoder().decode(decryptUserInfo.getIv());
//            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
//            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(ivBytes));
//            byte[] result = cipher.doFinal(Base64.getDecoder().decode(decryptUserInfo.getEncryptedData()));
//            jsonObject = JSONObject.parseObject(new String(result, StandardCharsets.UTF_8));
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } catch (NoSuchPaddingException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } catch (InvalidKeyException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } catch (InvalidAlgorithmParameterException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } catch (IllegalBlockSizeException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        }
//        return jsonObject;
        String openId = UserContext.getOpenId();
        String sessionKey = UserContext.getSessionKey();
        String s = decryptData(decryptUserInfo.getEncryptedData(), decryptUserInfo.getSessionKey(), decryptUserInfo.getIv());
        return JSONObject.parseObject(s);
    }

    private String cleanBase64String(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }

        // 移除非 Base64 合法字符
        String cleaned = input.replaceAll("[^A-Za-z0-9+/]", "");

        // 使用 StringBuilder 替代 repeat()
        int padding = 4 - (cleaned.length() % 4);
        if (padding < 4) {
            StringBuilder sb = new StringBuilder(cleaned);
            for (int i = 0; i < padding; i++) {
                sb.append('=');
            }
            cleaned = sb.toString();
        }

        return cleaned;
    }


    /**
     * 解密微信小程序加密数据
     */
    public String decryptData(String encryptedData, String sessionKey, String iv) {

        try {
            encryptedData = cleanBase64String(encryptedData);
            sessionKey = cleanBase64String(sessionKey);
            iv = cleanBase64String(iv);
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            if (keyBytes.length != 16 || ivBytes.length != 16) {
                throw new IllegalArgumentException("密钥或初始向量长度不正确");
            }

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据解密失败", e);
        }
    }

    // 解密后数据结构
//    {
//        "nickName": "微信用户",
//            "gender": 1,
//            "avatarUrl": "https://thirdwx.qlogo.cn/...",
//            "country": "中国",
//            "province": "北京",
//            "city": "朝阳区"
//    }

    @Override
    public JSONObject editTUserAndTCompany(TUser param) {
        TCompany tCompany = param.getTCompany();
        if (ObjectUtils.isEmpty(tCompany.getCompanyId())) {
            tCompany.setCompanyId(IdUtil.getSnowflakeNextId());
        }
        // 保存公司信息
        tCompanyService.saveOrUpdate(tCompany);

        // 保存用户信息
        TUser tUser = this.getBaseMapper().selectById(param.getUserId());
        tUser.setCompanyId(tCompany.getCompanyId());
        tUser.setUserName(param.getUserName());
        tUser.setUserPhone(param.getUserPhone());
        tUser.setRole(RoleEnum.ADMIN.getCode());
        this.saveOrUpdate(tUser);

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("openId", tUser.getOpenId());
        claims.put("userId", tUser.getUserId());
        claims.put("userCategory", tUser.getUserCategory());
        claims.put("companyId", tCompany.getCompanyId());
        String token = JWTUtil.createToken(claims);
        JSONObject res = new JSONObject();
        res.put("token",token);
        res.put("openId",tUser.getOpenId());
        res.put("userInfo",tUser);
        return res;
    }
}




